import { getData } from '@vimi/utils-api'
import { cascaderParse } from '@vimi/utils-tool'
import { SERVICE_NAME } from '@/credit/plugins/constant'

const state = {
  industrialClass: [],
  industrialClassTree: [],
}

const getters = {
  industrialClass: state => state.industrialClass,
  industrialClassTree: state => state.industrialClassTree,
}

const actions = {
  async getIndustrialClass({ commit }, force = false) {
    if (!force && state.industrialClass.length) {
      return Promise.resolve(state.industrialClass)
    }

    await getData(SERVICE_NAME, 'industrial_class', {}, { order_num: 'asc' }).then(res => {
      const data = (res && res.data) || []
      commit('industrialClass', data)
      commit(
        'industrialClassTree',
        cascaderParse({
          data,
          key: 'ind_class_code',
          parentKey: 'parent_code',
          topValue: '',
        })
      )
      return data
    })
  },
}

const mutations = {
  industrialClass: (state, payload) => (state.industrialClass = payload),
  industrialClassTree: (state, payload) => (state.industrialClassTree = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
